package cn.wolfcode.luowowo.article.service.impl;

import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.domain.TravelContent;
import cn.wolfcode.luowowo.article.mapper.TravelContentMapper;
import cn.wolfcode.luowowo.article.mapper.TravelMapper;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.ITravelService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

@Service
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelMapper travelMapper;

    @Autowired
    private TravelContentMapper travelContentMapper;

    public PageInfo<Travel> query(TravelQuery qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<Travel> list = travelMapper.selectForList(qo);
        return new PageInfo<>(list);
    }


    public Long saveOrUpdate(Travel travel) {

        //文章简介
        String string = travel.getTravelContent().getContent();
        if (string.length() > 200) {
            travel.setSummary(string.substring(0, 200));
        } else {
            travel.setSummary(string);
        }

        //最后更新时间
        travel.setLastUpdateTime(new Date());
        //保存或修改
        if (travel.getId() == null) {
            travel.setCreateTime(new Date());
            travelMapper.insert(travel);

            //插入文章
            TravelContent content = travel.getTravelContent();
            content.setId(travel.getId());
            travelContentMapper.insert(content);
        } else {
            travelMapper.updateByPrimaryKey(travel);

            //更新文章
            TravelContent content = travel.getTravelContent();
            content.setId(travel.getId());
            travelContentMapper.update(content);
        }
        return travel.getId();
    }

    public Travel get(Long id) {
        return travelMapper.selectByPrimaryKey(id);
    }

    public TravelContent getContent(Long id) {
        return travelContentMapper.selectById(id);
    }

    public List<Travel> getTop3() {
        return travelMapper.selectTop3();
    }

    public List<Travel> list() {
        return travelMapper.selectAll();
    }

    public List<Travel> get2TravelByUserId(Long id) {

        return travelMapper.select2TravelByUserId(id);
    }

}
